package com.example.sample.activity;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.view.View;

import com.example.app.BaseActivity;
import com.example.sample.R;

import net.liteheaven.XbApp;
import net.liteheaven.xblib.common.log.XLog;

import androidx.core.app.NotificationCompat;

import static android.app.NotificationManager.IMPORTANCE_DEFAULT;

/**
 * 结论1：
 * NotificationManager#notify的ID相当于一个句柄，用于NotificationManager#cancel来取消
 *
 * 结论2：
 * 不同的通知使用重复的PendingIntent请求码好像不会冲突（区别于AlarmManager）
 *
 * 结论3：
 * 安卓8.0以后的通知渠道一旦创建，其属性就不能被代码修改，假如app本身会播放mp3文件，且创建了一个IMPORTANCE_DEFAULT的渠道，容易和通知默认音乐形成双响
 * 重要等级<IMPORTANCE_DEFAULT时不会响。响的条件是重要等级>=IMPORTANCE_DEFAULT且存在soundUri
 */
public class NotificationAndPendingIntentActivity extends BaseActivity {

    private static final String OLD_CHANNEL_ID = "1001";
    private static final String CHANNEL_ID = "1004";
    private static final int NOTIFY_ID = 101;
    private static final int REQUEST_ID = 11;
    private NotificationManager notificationManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notification_and_pending_intent);

        notificationManager = (NotificationManager) this.getSystemService(android.content.Context.NOTIFICATION_SERVICE);

        findViewById(R.id.notify101).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Context ctx = NotificationAndPendingIntentActivity.this;
                createDefaultChannel(ctx);
                String tickerText = ctx.getResources().getString(R.string.app_name);
                Intent intent = new Intent(ctx, NotificationAndPendingIntentActivity.class);
                PendingIntent pi = PendingIntent.getActivity(ctx, REQUEST_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                Notification note = new NotificationCompat.Builder(ctx, CHANNEL_ID)
                        .setTicker(tickerText)
                        .setSmallIcon(R.drawable.ic_launcher)
                        .setContentText("内容101")
                        .setContentTitle("标题101")
                        .setContentIntent(pi)
                        .setAutoCancel(true)
                        .build();

                notificationManager.notify(NOTIFY_ID, note);

                if (!isSoundOn(ctx)){
                    vibrate();
                }
            }
        });
        findViewById(R.id.cancelNotify101).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                notificationManager.cancel(NOTIFY_ID);
            }
        });

        findViewById(R.id.notify102).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Context ctx = NotificationAndPendingIntentActivity.this;
                createDefaultChannel(ctx);
                String tickerText = ctx.getResources().getString(R.string.app_name);
                Intent intent = new Intent(ctx, MainActivity.class);
                PendingIntent pi = PendingIntent.getActivity(ctx, REQUEST_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                Notification note = new NotificationCompat.Builder(ctx, CHANNEL_ID)
                        .setTicker(tickerText)
                        .setSmallIcon(R.drawable.ic_launcher)
                        .setContentText("内容102")
                        .setContentTitle("标题102")
                        .setContentIntent(pi)
                        .setAutoCancel(true)
                        .build();

                notificationManager.notify(102, note);
            }
        });

        removeOldChannel(this);
    }

    /**
     * app启动后尽早调用，因为删除会把通知栏已有的通知干掉
     * @param context
     */
    public static void removeOldChannel(Context context){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            log("removeOldChannel");
            NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.deleteNotificationChannel(OLD_CHANNEL_ID);
        }
    }

    public static void createDefaultChannel(Context context){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationChannel channel = notificationManager.getNotificationChannel(CHANNEL_ID);
            if (channel == null){
                log("createNotificationChannel");
                channel = new NotificationChannel(CHANNEL_ID, "常规通知", IMPORTANCE_DEFAULT);
                //hannel.setSound(null, null);
                //channel.setVibrationPattern(null);
                notificationManager.createNotificationChannel(channel);
            }
        }
    }

    private static void vibrate(){
        final long[] pattern = {10, 200, 200, 200};
        Vibrator vibrator = (Vibrator) XbApp.getInstance().getContext().getSystemService(VIBRATOR_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            VibrationEffect ve = VibrationEffect.createWaveform(pattern, -1);
            vibrator.vibrate(ve);
        }else{
            vibrator.vibrate(pattern, -1);
        }
    }

    private boolean isSoundOn(Context context){
        boolean result = false;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationChannel channel = notificationManager.getNotificationChannel(CHANNEL_ID);
            if (channel != null && channel.getImportance() >= IMPORTANCE_DEFAULT && channel.getSound() != null){
                result = true;
            }
        }
        return result;
    }

    private static void log(String log){
        XLog.d(NotificationAndPendingIntentActivity.class.getSimpleName(), log);
    }
}
